<template>
  <el-dialog
    :title="showTitle"
    :visible="dialogVisible"
    @close="closeDialog"
  >
    <el-form
      ref="roleDialogForm"
      label-width="80px"
      :model="roleForm"
      :rules="rules"
    >
      <el-form-item
        prop="name"
        label="角色"
      >
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="roleForm.description" type="textarea" row="3" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button v-loading="loading" type="primary" @click="handlerSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addRoleApi, updateRoleApi } from '@/api/setting'
export default {
  components: {},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleForm: {
        // name: '', // 角色名
        // description: '' // 描述
      }, // 角色表单
      rules: {
        name: [
          {
            required: true, message: '角色名 必填', trigger: 'blur'
          }
        ]
      }, // 校验规则
      loading: false
    }
  },
  computed: {
    showTitle() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:dialogVisible', false)
      this.$refs.roleDialogForm.resetFields()
      this.roleForm = {

      }
    },
    async handlerSubmit() {
      // 发请求拿数据
      try {
        // 校验表单
        await this.$refs.roleDialogForm.validate()
        this.loading = true
        // 调用接口
        this.roleForm.id ? await updateRoleApi(this.roleForm) : await addRoleApi(this.roleForm)
        // 提示用户
        this.$message.success(`角色${this.roleForm.id ? '编辑' : '添加'}成功`)
        // 关闭弹窗
        this.closeDialog()
        // 修改视图层
        this.$parent.getRole()
        // $parent 缺点：要保证 组件的位置 放的正确 局限性比较大 不够灵活
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
